package com.gba.mark.exam.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gba.mark.exam.entity.ExamAnswer;
import com.gba.mark.exam.entity.ExamPaper;
import com.gba.mark.exam.entity.ExamQuestions;
import com.gba.mark.exam.entity.ExamResult;
import com.gba.mark.exam.entity.dto.ExamAnswerDto;
import com.gba.mark.exam.mapper.ExamAnswerMapper;
import com.gba.mark.exam.mapper.ExamPaperMapper;
import com.gba.mark.exam.mapper.ExamQuestionsMapper;
import com.gba.mark.exam.service.ExamAnswerService;
import com.gba.mark.exam.service.ExamPaperService;
import com.gba.mark.exam.service.ExamResultService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.geom.QuadCurve2D;
import java.util.Date;
import java.util.List;

@Service
public class ExamAnswerImpl extends ServiceImpl<ExamAnswerMapper, ExamAnswer> implements ExamAnswerService {

    @Resource
    private ExamAnswerService examAnswerService;

    @Resource
    private ExamPaperMapper examPaperMapper;

    @Resource
    private ExamQuestionsMapper examQuestionsMapper;

    @Resource
    private ExamResultService examResultService;

    /**
     * 保存并更新一份用户输入的答案
     */
    @Override
    public boolean saveAnswer (List<ExamAnswerDto> examAnswerDto, Integer userId, Integer groupId) {

        String questionIds = examPaperMapper.selectOne(
                new QueryWrapper<ExamPaper>().select("question_ids").eq("group_id", groupId)
        ).getQuestionIds();

        JSONObject relAnswerId = JSON.parseObject(questionIds);
        JSONObject userAnswers = new JSONObject();

        int index = 0;
        float correct = 0f;
        for (ExamAnswerDto ed : examAnswerDto) {
            String userAnswer = ed.getAnswer();
            String relAnswer = examQuestionsMapper.selectOne(
                    new QueryWrapper<ExamQuestions>().eq("id", relAnswerId.get(++index))
            ).getAnswer();
            userAnswer = userAnswer.trim();
            relAnswer = relAnswer.trim();
            if (userAnswer.equals(relAnswer)) {
                ++correct;
            }
            userAnswers.put(String.valueOf(ed.getIndex()), userAnswer);
        }

        return examAnswerService.save(
                new ExamAnswer().setUserAnswer(userAnswers.toString())
                .setUserId(userId).setGroupId(groupId).setSubmitTime(new Date())) &&
                examResultService.save(new ExamResult().setScore(correct/index)
                .setUserId(userId).setGroupId(groupId)
        );
    }

 }
